import { TransformInterceptor } from './interceptors/transform.interceptor';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import { WsAdapter } from '@nestjs/platform-ws';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { join } from 'path';
import { ConfigService } from '@nestjs/config';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { ApiConfig, ApiConfigKit } from 'tnwx';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
declare const module: any;

async function bootstrap() {

  // 创建Nest应用程序实例
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const configService = app.get(ConfigService);

  // 添加前缀
  // app.setGlobalPrefix('api');

  // Swagger 文档
  const options = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, options, { ignoreGlobalPrefix: true });
  SwaggerModule.setup('api', app, document);

  // 初始化微信应用相关配置
  const configs: ApiConfig[] = Object.values(configService.get('WX_CONFIG'));
  console.log('configs',configs)
  configs.forEach(config => ApiConfigKit.putApiConfig(config));

  // 日志打印和记录
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  // 处理跨域 
  app.enableCors();
  
  // 注册全局异常过滤器 
  app.useGlobalFilters(new HttpExceptionFilter());
  // 注册全局响应拦截
  app.useGlobalInterceptors(new TransformInterceptor());
  // 添加请求参数自动校验
  app.useGlobalPipes(new ValidationPipe({ 
    transformOptions: {
      enableImplicitConversion: true // 进行ts反射类型装换
    }
  }));
 
  // 设置静态资源路 prefix 可以设置虚拟路径
  app.useStaticAssets(join(__dirname, '..', configService.get('ASSETS').root), { prefix: configService.get('ASSETS').prefix });

  // 启动websocket
  app.useWebSocketAdapter(new WsAdapter(app));
  // app.useWebSocketAdapter(new RedisIoAdapter(app));

  await app.listen(configService.get('port'));

  // HMR 
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}
bootstrap();
